<?php 

/* Copyright 2010 John Hooley

	  
    This file is part of Portfolio Zen.



    Portfolio Zen is free software: you can redistribute it and/or modify

    it under the terms of the GNU General Public License as published by

    the Free Software Foundation, either version 3 of the License, or

    (at your option) any later version.



    Portfolio Zen is distributed in the hope that it will be useful,

    but WITHOUT ANY WARRANTY; without even the implied warranty of

    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

    GNU General Public License for more details.



    You should have received a copy of the GNU General Public License

    along with Portfolio Zen.  If not, see <http://www.gnu.org/licenses/>.

 */ 



defined('_JEXEC') or die( 'Restricted access' );

jimport( 'joomla.application.component.model');

class PortfoliozenModelGallery extends JModel {

  public function load($id, $type = "gallery"){
    if($id > 0) $ajax = json_encode($this->_buildContent($id, $type));
    return $ajax;
  }

  private function _buildContent($id, $type) {
    $results = $this->_queryArticles($id);
    $type = ($type == 'gallery') ? 'Image' : 'Caption';
    return $this->_extractItem($results, $type);
  }

  private function _extractItem($arr, $type){
    $result = array();
    foreach($arr as $value){
      $matches = array();
      $match = call_user_func(array($this, "_regex".$type), $value);
      $result[] = $match;
    }
    $result = array("items" => $result);
    return $result;
  }

  private function _regexImage($value){
      $matches = array();
      $pattern = "|<img[^>]+\/>|";
      preg_match_all($pattern, $value, $matches);
      $match = preg_replace('|(.)+src ?= ?"([^"]+)"(.)*|', "$2", $matches[0][0]);
      return array("large" => JURI::base() . $match);
  }

  private function _regexCaption($value){
      $matches = array();
      $pattern = '|<p>((?!<\/?p>)(?!<img).)*<\/p>|';
      preg_match_all($pattern, $value, $matches);
      return $result = array("content" => str_replace(array('<p>', '</p>'), '', $matches[0][0]));
  }

  private function _queryArticles($id){
    $db =& JFactory::getDBO(); 
    $sql = "SELECT " . $db->nameQuote('introtext') . " FROM #__content WHERE "
      . $db->nameQuote('catid') . " = " . $db->quote($id) . " AND ". $db->nameQuote('state') . "
 = " . $db->quote('1') . " ORDER BY " . $db->nameQuote('ordering') . " ASC";
    $db->setQuery($sql);
    return $db->loadResultArray();
  }
   
}
